#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/param.h>
#include "typedef.h"
#include "common.h"

#define MAX_NAME     (256)
#define MAX_SECTION  (1024)
#define BUF_LEN      (1024)

typedef struct _Section
{
	char section[MAX_NAME];
	char data[MAX_SECTION];
	struct _Section *next;
}SECTION, *PSECTION;

static FILE *file = NULL;
static const char* configuration_file_path = {"/root/bin/tmc.conf"};

static PSECTION sectionheader = NULL;
static PSECTION sectiontail = NULL;

static void read_conf();
static char* clean(char* p);

int cfg_init()
{
	if ( (file = fopen(configuration_file_path, "r")) == NULL )
	{
		return FATAL;
	}

	read_conf();

	fclose(file);

	return SUCCESS;
}

int cfg_getnumber(char* section)
{
	PSECTION p = sectionheader;
	while(p)
	{
		if (strcmp(p->section, section) == 0)
			return atoi(p->data);
		p = p->next;
	}

	return -1;
}

int cfg_getstring(char* section, char* buffer, int bufSize)
{
	PSECTION p = sectionheader;
	while(p)
	{
		if (strcmp(p->section, section) == 0
				&& strlen(p->data) < bufSize)
		{
			strcpy(buffer, p->data);
			return SUCCESS;
		}
		p = p->next;
	}

	return ERROR;
}

void cfg_release()
{
	if (!sectionheader)
		return;

	PSECTION temp = sectionheader;
	while(temp)
	{
		sectionheader = temp->next;
		free(temp);
		temp = sectionheader;
	}

	sectionheader = NULL;
}

void read_conf()
{
    char *p;
	char buffer[BUF_LEN];
	char lbuf[BUF_LEN];
	char rbuf[BUF_LEN];
	while ( fgets( buffer, BUF_LEN, file ) )
	{
		if ((p = clean(buffer)) == NULL)
			continue;

		if (!sprit(p, '=', lbuf, rbuf))
		    continue;

		trim(lbuf);
		trim(rbuf);

		PSECTION temp = (PSECTION)malloc(sizeof(SECTION));
		memcpy(temp->section, lbuf, MIN(MAX_NAME, strlen(lbuf) + 1));
		memcpy(temp->data, rbuf, MIN(MAX_SECTION, strlen(rbuf) + 1));

		if (sectionheader == NULL)
			sectionheader = temp;
		else
			sectiontail->next = temp;
		sectiontail = temp;
	}
}

char* clean(char* p)
{
	trim(p);
	char* head = p;
	while(*p != '\0')
	{
		if (*p == '#' || *p == '\n')
		{
			*p = '\0';
			break;
		}
		p++;
	}

	if (*head == '\0')
		return NULL;
	return head;
}





